<template>
  <a-drawer
    v-model:visible="visible"
    :width="340"
    unmount-on-close
    @ok="save"
    @cancel="close"
  >
    <template #title>
      {{ role.roleName }}
    </template>
    <div>
      <a-tree
        ref="menuTreeRef"
        v-model:checked-keys="checkedKeys"
        :checked-strategy="'all'"
        :field-names="fieldNames"
        :data="menuTree"
        :checkable="true"
        :show-line="true"
        :only-check-leaf="true"
      >
        <template #icon="{node}">
          <component :is="node.meta.icon" v-if="node.meta.icon" />
          <icon-safe v-else />
        </template>
      </a-tree>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, defineExpose, defineEmits } from 'vue';
import { rolePermission, setPermission, SysRole } from '@/api/system/role';
import { menuTreeSelect } from '@/api/system/menu';
import { Message } from '@arco-design/web-vue';

const emits = defineEmits(['submit']);

const visible = ref<boolean>(false);

const role = ref<SysRole>({});

const fieldNames = ref({
  key: 'menuId',
  title: 'menuName',
  children: 'children'
});

const menuTreeRef = ref();

const checkedKeys = ref<string[]>([]);

const menuTree = ref({});

const save = async () => {
  const halfCheckedNodes = menuTreeRef.value.getHalfCheckedNodes().map((item: { menuId: any; }) => item.menuId);
  await setPermission({
    roleId: role.value.roleId,
    checked: checkedKeys.value,
    halfChecked: halfCheckedNodes
  });
  Message.success('操作成功');
  close();
  emits('submit');
};

const open = async (record: SysRole) => {
  role.value = record;
  const { data } = await rolePermission(record.roleId);
  const menuResp = await menuTreeSelect();
  menuTree.value = menuResp.data;
  checkedKeys.value = data;
  visible.value = true;
};

const close = () => {
  visible.value = false;
};
defineExpose({
  open,
  close
});
</script>

<script lang="ts">
export default {
  name: 'DrawerPermission'
};
</script>

<style scoped>

</style>